package com.zrf.gulimall.product.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrf.gulimall.common.database.utils.PageUtils;
import com.zrf.gulimall.common.database.utils.Query;
import com.zrf.gulimall.product.dao.BrandDao;
import com.zrf.gulimall.product.entity.BrandEntity;
import com.zrf.gulimall.product.entity.CategoryBrandRelationEntity;
import com.zrf.gulimall.product.service.BrandService;
import com.zrf.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

	@Resource
	CategoryBrandRelationService categoryBrandRelationService;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String key = (String) params.get("key");
		IPage<BrandEntity> page = this.lambdaQuery()
				.eq(StrUtil.isNotEmpty(key), BrandEntity::getBrandId, key)
				.or()
				.like(StrUtil.isNotEmpty(key), BrandEntity::getName, key)
				.page(new Query<BrandEntity>().getPage(params));
		return new PageUtils(page);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void updateDetails(BrandEntity brand) {
		baseMapper.updateById(brand);
		if (StrUtil.isNotEmpty(brand.getName())) {
			categoryBrandRelationService.updateBrand(brand.getBrandId(), brand.getName());
		}
	}

	@Override
	public List<BrandEntity> queryByCatalogId(Long catId) {
		List<CategoryBrandRelationEntity> relationEntities = categoryBrandRelationService.queryByCatalogId(Collections.singletonList(catId));
		List<Long> brandIdList = relationEntities.stream().map(CategoryBrandRelationEntity::getBrandId).distinct().collect(Collectors.toList());
		if (CollUtil.isEmpty(brandIdList)) {
			return null;
		}
		return this.listByIds(brandIdList);
	}

	@Override
	public void delete(List<Long> brandIdList) {
		this.removeByIds(brandIdList);
		categoryBrandRelationService.remove(
				Wrappers.<CategoryBrandRelationEntity>lambdaQuery()
						.in(CategoryBrandRelationEntity::getBrandId, brandIdList)
		);
	}

}